<template>
  <div class="message-notice">
    <div class="search-box">
      <FilterSearch
        class="filter-css"
        :filtersList="filtersLists"
        :btnProps="btnProps"
        @query="handleSearchBtn"
        @reset="handleSearchBtn"
        ref="FilterDom"
      />
      <button @click="postMessage()">Send message</button>
      <div>{{ message }}</div>
      <div>{{ error }}</div>
      <addButton @click="addInfo" title="新增" />
      <CommonTable
        ref="CommonTable"
        overflowText
        :loading="tableLoading"
        :tableLabel="tableHeaders"
        :data="tableData"
        :pageInfo="pageInfos"
        @handleTableButton="handleTableButton"
        @handleGetList="handleSizeChange"
        @seeDetails="seeDetails"
        :option="tableOptions"
      ></CommonTable>
    </div>
    <div class="Dialog">
      <Dialog
        :title="changePasswordDialog.title"
        :append-to-body="true"
        :width="changePasswordDialog.type !== 'tabsDetails' ? '30%' : '18%'"
        top="15vh"
        v-model="changePasswordDialog.visible"
        :showFooterBtn="changePasswordDialog.type === 'add'"
        @confirm="handleDialogConfirm"
        @close="handleDialogClose"
      >
        <div class="edit" v-if="changePasswordDialog.type !== 'tabsDetails'">
          <el-form
            ref="formRef"
            :model="detailFormData"
            label-width="140px"
            class="demo-ruleForm"
            :rules="changePasswordDialog.type === 'add' ? rules : {}"
          >
            <el-form-item label="消息标题：" prop="msgTitle">
              <el-input v-model="detailFormData.msgTitle" :disabled="changePasswordDialog.type === 'detail'"></el-input>
            </el-form-item>
            <el-form-item label="消息内容：" prop="msgContent">
              <el-input v-model="detailFormData.msgContent" type="textarea" :rows="5" :disabled="changePasswordDialog.type === 'detail'"></el-input>
            </el-form-item>
            <el-form-item label="责任部门/责任人：" v-if="changePasswordDialog.type === 'add'" prop="receiveUserIds">
              <el-badge :value="detailFormData.receiveUserIds.length" class="item">
                <el-button size="small" @click="chooseOrg">点击选择</el-button>
              </el-badge>
            </el-form-item>
          </el-form>
        </div>
        <div class="tabs" v-else>
          <el-tabs v-model="activeName" style="width: 100%">
            <el-tab-pane :label="`未读用户(${unReadList.length})`" name="first">
              <ul>
                <li v-for="item in unReadList" :key="item.id" style="padding: 2px 0; margin-bottom: 10px; border-bottom: 1px solid #ddd; color: red">
                  {{ item.userName }}
                </li>
              </ul>
            </el-tab-pane>
            <el-tab-pane :label="`已读用户(${readList.length})`" name="second">
              <!-- <ul style="height: 500px; overflow: auto"> -->
              <ul>
                <li v-for="item in readList" :key="item.id" style="padding: 2px 0; margin-bottom: 10px; border-bottom: 1px solid #ddd; color: green">
                  {{ item.userName }}
                </li>
              </ul>
            </el-tab-pane>
          </el-tabs>
        </div>
      </Dialog>
      <OrgTree
        v-model="nodeTreeOptions.orgVisible"
        showCheckBoX
        :selectedIdArr="
          nodeTreeOptions.defaultCheck.map((item) => {
            return item.id
          })
        "
        @handleSelectionChange="handleSelectionOrg"
        @orgConfirm="handleConfirmSelectOrg"
      ></OrgTree>
      <FileDialog v-model="dialogAppendixVisible" title="附件" :id="fileInfo.id" :tableType="fileInfo.tableType" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, computed, reactive, ref } from 'vue'
  import { useStore } from 'store/index'
  import { $msgBox } from '@/utils/messageBox'
  import {
    useState
  } from '@/store/hooks'
  import messageNotice from './data/index'
import useWebWorker from '@/hooks/useWorker'
  let { filtersListData, btnPropsData, tableHeaderData, tableOptionsData, paramsData, pageInfo, rules } = messageNotice
  interface pageData {
    totalCount: number
    pageIndex: number
    pageSize: number
  }
  interface tableOptionData {
    label: string
    width: string
    fixed: string
    children: any[]
  }
  interface tableHeaderItem {
    label: string
    prop: string
    width: string
  }
  interface btnPropsType {
    list: Array<any>
  }
  interface detailFormDataType {
    msgTitle: string
    msgContent: string
    receiveUserIds: Array<number>
  }
  interface FileInfoType {
    id: string | number
    tableType: string
  }
  interface NodeTreeOptionsType {
    orgVisible: boolean
    dataSource: number
    defaultCheck: Array<any>
  }
  const filtersLists = reactive<Array<any>>(filtersListData)
  const btnProps = reactive<btnPropsType>(btnPropsData)
  const tableLoading = ref<boolean>(false)
  const tableHeaders = reactive<Array<tableHeaderItem>>(tableHeaderData)
  const tableData = ref<Array<any>>([])
  //  已读用户
  const readList = ref<Array<any>>([])
  //  未读用户
  const unReadList = ref<Array<any>>([])
  // 附件弹窗
  const dialogAppendixVisible = ref<boolean>(false)
  const fileInfo = reactive<FileInfoType>({
    id: '',
    tableType: ''
  })
  const pageInfos = reactive<pageData>(pageInfo)
  const params = reactive({ ...paramsData, page: pageInfos.pageIndex, rows: pageInfos.pageSize })
  const tableOptions: tableOptionData = reactive(tableOptionsData)
  //   控制弹窗
  const changePasswordDialog = reactive({
    title: '',
    visible: false,
    type: ''
  })
  //  表单重置
  const fromRest = () => {
    const fromRestData: detailFormDataType = {
      msgTitle: '',
      msgContent: '',
      receiveUserIds: []
    }
    return fromRestData
  }
  const nodeTreeOptions = reactive<NodeTreeOptionsType>({
    orgVisible: false,
    dataSource: 2,
    defaultCheck: []
  })
  const detailFormData = reactive<detailFormDataType>(fromRest())
  const formRef = ref<any>(null)
  const activeName = ref<string>('first')
  const userInfo = computed(() => store.state.app.userInfo) as any
  const store = useStore()
  //   请求列表数据
  const getList = () => {
  }
  //   删除消息
  const getListDelete = (e: number) => {
  }
  //  保存新增
  const getAddSave = (e: object) => {
  }
  // 表单查询
  const handleSearchBtn = (item: any, otherBtns: any): void => {
    params.sendTimeStart = item.query.time && item.query.time[0]
    params.sendTimeEnd = item.query.time && item.query.time[1]
    params.msgTitle = item.query.msgTitle
    params.msgType = item.query.msgType
    getList()
    console.log('handelClick按钮', item, otherBtns)
    const app = useState('app', ['requestCount'])
    console.log('useHook', app.requestCount);
  }
  const handleTableButton = ({ methods, row }: { methods: any; row: any }): void => {
    console.log('methods', methods, 'row', row)
    switch (methods) {
      case 'detail':
        changePasswordDialog.title = '详情'
        changePasswordDialog.visible = true
        changePasswordDialog.type = 'detail'
        detailFormData.msgTitle = row.msgTitle
        detailFormData.msgContent = row.msgContent
        break
      case 'more':
        fileInfo.id = row.id
        fileInfo.tableType = row.tableType
        dialogAppendixVisible.value = true
        break
      case 'delete':
        $msgBox('是否执行删除？', '提示')
          .then((res) => {
            getListDelete(row.id)
          })
          .catch((err) => {})
        break
    }
  }
  const seeDetails = ({ methods, row }: { methods: any; row: any }): void => {
    readList.value = []
    unReadList.value = []
    changePasswordDialog.visible = true
    changePasswordDialog.title = '阅读情况'
    changePasswordDialog.type = 'tabsDetails'

    if (!row.receiveUserIds) return
    const receiveUserIds = row.receiveUserIds
    receiveUserIds.forEach((item: any, index: number) => {
      if (item.readTag === 0) {
        unReadList.value.push(item)
      } else {
        readList.value.push(item)
      }
    })
  }

  const handleSizeChange = (pages: any): void => {
    pageInfos.pageIndex = params.page = pages.page
    pageInfos.pageSize = params.rows = pages.limit
    getList()
    console.log('pages', pages)
  }
  // 点击弹窗确定按钮
  const handleDialogConfirm = () => {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        getAddSave(detailFormData)
      }
    })
  }
  //  点击关闭弹窗
  const handleDialogClose = () => {
    changePasswordDialog.visible = false
    Object.assign(detailFormData, fromRest())
    nodeTreeOptions.defaultCheck = []
    console.log(detailFormData, '表单数据')
  }
  const addInfo = () => {
    changePasswordDialog.title = '新增'
    changePasswordDialog.visible = true
    changePasswordDialog.type = 'add'
    console.log('新增')
  }
  //确认勾选
  const handleSelectionOrg = (list: Array<number | string>, change?: any): void => {
    console.log(list, 'list---------')

    list.map((item: any) => {
      nodeTreeOptions.defaultCheck.push({ adminUserId: item.adminUserId, id: item.id })
    })
    change.remove.map((item: any) => {
      let nodeIndex = 0
      nodeTreeOptions.defaultCheck.map((node, index) => {
        if (node.id === item) {
          nodeIndex = index
          return
        }
      })
      nodeTreeOptions.defaultCheck.splice(nodeIndex, 1)
    })
    nodeTreeOptions.defaultCheck = unique(nodeTreeOptions.defaultCheck)
  }
  const unique = (arr: any) => {
    const res = new Map()
    return arr.filter((arr: any) => !res.has(arr.id) && res.set(arr.id, 1))
  }
  const handleConfirmSelectOrg = () => {
    let arrList: any = []
    nodeTreeOptions.defaultCheck.map((item: any) => {
      arrList.push(item.adminUserId)
    })
    detailFormData.receiveUserIds = arrList
  }
  const chooseOrg = () => {
    nodeTreeOptions.orgVisible = true
    // let defaultCheckArr: any = []
    // detailFormData.receiveUserIds.map((item: any) => {
    //   defaultCheckArr.push({id:item})
    // })
  }
  const workerScript = function() {
    self.onmessage = function(e) {
      let count = 0
      for (let i = 0, len = 5; i < len; i++) {
        count += i
      }
      console.log(count, 'webWorker');
      // self.postMessage('Worker received: ' + e.data); 
    };
  };
  const {
    postMessage,
    message,
    error
  } = useWebWorker(workerScript)
  onMounted(async () => {
  })
</script>
<style lang="scss" scoped>
  .message-notice {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    .search-box {
      width: 100%;
      //   height: 100%;
      box-sizing: border-box;
      padding: 0 20px;
      .filter-css {
        margin-top: 20px;
        margin-left: 30px;
      }
    }
  }
</style>
